import React, { useState } from 'react';
import { useHistory } from 'react-router';
import './css/login.css';
import { useAuth } from './AuthProvider';

const Login = () => {
    const {isLogin,setIsLogin} = useAuth();
    const [val, setVal] = useState('')
    const [val1, setVal1] = useState('')
    const [res, setRes] = useState({})
    const history = useHistory();

    const login = () => {
        setRes({
            token: true
        })
        fetch('https://www.h5fd.xyz:2021/test/login', {
            method: 'POST',
            body: JSON.stringify({ username: val, passwd: val1 })
        })
            .then(res => res.json())
            .then(res => {
                setRes(res)
                setIsLogin(true);
                sessionStorage.setItem('user',JSON.stringify(res))
                sessionStorage.setItem('isLogin',true)
                history.replace('/alter');
            })
            .catch(res => {
                setRes({ err: true })
            })
    }

    return (
        <div className='loginBox'>
            <img src="https:www.h5fd.xyz:2021/test/headImg/logo.png" alt="" />
            <div className="login">
                <h1 className="title">管理员登录</h1>
                <br />
                <input className="loginInput" placeholder='请输入账号' type="text" onChange={(e) => setVal(e.target.value)} /> <br /><br />
                <input className="loginInput" placeholder='请输入密码' type="password" onChange={(e) => setVal1(e.target.value)} /> <br /><br />
                <button className="lobtn" onClick={login}>登录</button>
                {isLogin
                    ? <>登陆成功</>
                    : res.err
                        ? <div>登录失败</div>
                        : ''
                }
            </div>
        </div>
    );
}

export default Login;